package pkg

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"strconv"
	"time"
)

const APP_KEY = "2306a"

type Jwt struct {
}

func NewJwt() *Jwt {
	return &Jwt{}
}

func (j *Jwt) TokenEncode(userid int) (tokenString string, err error) {
	// 颁发一个有限期一小时的证书
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"user_id": strconv.Itoa(userid),
		"exp":     time.Now().Add(time.Hour * time.Duration(1)).Unix(),
		"iat":     time.Now().Unix(),
	})
	tokenString, err = token.SignedString([]byte(APP_KEY))
	return tokenString, err
}

func (j *Jwt) TokenDecode(tokenString string) string {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:     '
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		return []byte(APP_KEY), nil
	})

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {

		userId := claims["user_id"].(string)
		fmt.Println(userId)
		return userId
		//拿到userID  要去  redis中校验  token是否合法
	} else {
		fmt.Println(err)
		return ""
	}

}
